<?php
namespace App\Services;
use App\Models\ActivityModel;
use App\Models\OrderModel;
use App\Models\MemberModel;
use App\Models\CourseModel;
use App\Models\TeachingAidModel;
use App\Models\ProductOrderModel;
use App\Models\OrderLogModel;
use App\Models\TeachingAidsModel;
use Illuminate\Support\Facades\DB;
use App\Models\GiveCourseMemberModel;

class OrderService{
    /**
     * 插入订单save
     * @param array $data
     * @return int $orderid
     */
    public function insertOrderBySave($data){
        $order = new OrderModel;
        $order->member_id = $data['member'];
        $order->product_type = 1;
        $order->ordernum = 'G-Course_'.date('YmdHis');
        $order->payment = $data['price'];
        $order->payment_type = 1;
        $order->postage = 0;
        $order->delivery_func = 1;
        $order->address_id = 0;
        $order->pay_status = 40;
        $order->composition_status = 50;
        $order->payment_time = date('Y-m-d H:i:s');
        $order->end_time = date('Y-m-d H:i:s');
        $order->add_date = date('Y-m-d H:i:s');
        $order->save();
        $orderid = $order->id;
        return $orderid;
    }

    /**
     * 插入订单商品信息
     * @param array $data
     * @return int $product_id
     */
    public function insertOrderProductBySave($data){
        $op = new ProductOrderModel();
        $op->order_id = $data['orderid'];
        $op->product_id = $data['courseid'];
        $op->num = 1;
        $op->save();
        $product_id = $op->id;
        return $product_id;
    }

    /**
     * 插入订单日志
     * @param array $data
     * @return int $order_log_id
     */
    public function insertOrderLogBySave($data){
        $orderlog = new OrderLogModel;
        $orderlog->order_id = $data['orderid'];
        $orderlog->ordernum = 'G-Course_'.date('YmdHis');
        $orderlog->pay_status = 40;
        $orderlog->action_note = '系统赠课，代付金额'.$data['price'].'元，成功';
        $orderlog->logtime = date('Y-m-d');
        $orderlog->save();
        $order_log_id = $orderlog->id;
        return $order_log_id;
    }

    /**
     * 插入赠课记录
     * @param array $data
     * @return int $give_course_log_id
     */
    public function insertGiveCourseLogBySave($data){
        $givecourse = new GiveCourseMemberModel;
        $givecourse->course_id = $data['courseid'];
        $givecourse->member = $data['member'];
        $givecourse->give_date = date('Y-m-d H:i:s');
        $givecourse->save();
        $give_course_log_id = $givecourse->id;
        return $give_course_log_id;
    }
    /**
     * 获取赠课信息
     * @param int $memberid
     * @return info $loginfo
     */
    public function getGiveCoureLogInfo($memberid){
        $loginfo = GiveCourseMemberModel::where('member',$memberid)->first();
        if(!empty($loginfo)){
            return $loginfo;
        }else{
            return false;
        }
    }

    /**
     * 添加赠课记录
     * @param array $data
     * @return bool $res
     */
    public function insertGiveCourseLog($data){
        $res = GiveCourseMemberModel::insert($data);
        return $res;
    }

    /**
     * 获取赠课记录列表
     * @param int $courseid
     * @return object $giveCourseList
     */
    public function getGiveCourseList($courseid,$userlist=array()){
        $giveCourseList = GiveCourseMemberModel::where('course_id',$courseid)
                        ->where(function($query) use ($userlist){
                            if(!empty($userlist)){
                                $query->whereIn('member',$userlist);
                            }
                        })
                        ->get()
                        ->toArray();
        if(!empty($giveCourseList)){
            return $giveCourseList;
        }else{
            return false;
        }
    }

    /**
     * 查询个人订单
     * @param int $member_id
     * @param int $product_id
     * @return array $orderinfo
     */
    public function getMemberOrderInfo($member_id,$product_id,$product_type = 0){
        $sql = "SELECT o.id,o.member_id,o.pay_status,o.composition_status,o.product_type,op.product_id FROM bgz_order o LEFT JOIN bgz_order_product op ON o.id = op.order_id WHERE";

        if($member_id != ''){
            if(is_array($member_id)){
                $nmember_id = implode(',',$member_id);
                $sql .= " o.member_id IN ({$nmember_id})";
            }else{
                $sql .= " o.member_id = {$member_id}";
            }

            if(is_array($product_id)){
                $nproduct_id = implode(',',$product_id);
                $sql .= " AND op.product_id IN ({$nproduct_id})";
            }else{
                $sql .= " AND op.product_id = {$product_id}";
            }

            if($product_type > 0){
                $sql .= " AND product_type = {$product_type}";
            }

            $sql .= " ORDER BY o.member_id desc,o.id desc,o.pay_status desc";

            if(!is_array($product_id) && !is_array($member_id)){
                $sql .= " LIMIT 1";
            }
        }else{
            if(is_array($product_id)){
                $nproduct_id = implode(',',$product_id);
                $sql .= " op.product_id IN ({$nproduct_id})";
            }else{
                $sql .= " op.product_id = {$product_id}";
            }

            if($product_type > 0){
                $sql .= " AND product_type = {$product_type}";
            }

            $sql .= " ORDER BY o.member_id desc,o.id desc,o.pay_status desc";
        }
        $orderinfo = DB::select($sql);
        return $orderinfo;
    }

    /**
     * 插入订单日志
     * @param array $data
     * @return bool $res
     */
    public function insertOrderLog($data){
        $res = OrderLogModel::insert($data);
        return $res;
    }

    /**
     * 插入订单
     * @param array $data
     * @return int  $orderId
     */
    public function insertOrder($data){
        $orderId = OrderModel::insertGetId($data);
        return $orderId;
    }

    /**
     * 插入订单商品
     * @param array $data
     * @return bool $res
     */
    public function insertOrderProduct($data){
        $res = ProductOrderModel::insert($data);
        return $res;
    }

    /**
     * 更改订单下商品总数
     * @param int $opid
     * @param array $data
     * @return bool $res
     */
    public function updateOrderProductNum($opid,$data){
        $res = ProductOrderModel::where('id',$opid)->update($data);
        return $res;
    }

    /**
     * 获取个人订单总数
     * @param int $member_id
     * @return int $num
     */
    public function getOrderNum($member_id){
        $num = OrderModel::where('member_id',$member_id)->select('id')->count();
        return $num;
    }

    /**
     * 获取订单信息
     * @param string $order_sn
     * @return array $orderInfo
     */
    public function getOrderInfoBySn($order_sn){
        $orderInfo = OrderModel::where('ordernum',$order_sn)->first()->toArray();
        if(empty($orderInfo)){
            return false;
        }

        return $orderInfo;
    }

    /**
     * 获取订单详细信息
     * @param int $id
     * @return array $orderInfo
     */
    public function getOrderInfo($id){
        $orderInfo = OrderModel::where('id',$id)->first()->toArray();

        if(!empty($orderInfo)){
            $orderInfo['product_list'] = ProductOrderModel::where('order_id',$id)->get()->toArray();

            $memberInfo = MemberModel::where('id',$orderInfo['member_id'])->select('nick','telephone')->first();
            if($orderInfo['member_id'] > 116 && $memberInfo->nick == base64_encode(base64_decode($memberInfo->nick))){
                $memberInfo->nick = base64_decode($memberInfo->nick);
            }

            $orderInfo['member_nick'] = $memberInfo->nick;
            $orderInfo['telephone'] = $memberInfo->telephone;

            switch($orderInfo['product_type']){
                case 1:
                    foreach($orderInfo['product_list'] as $optm=>$opst){
                        $orderInfo['product_list'][$optm]['productinfo'] = CourseModel::where('id',$opst['product_id'])->first()->toArray();
                        $orderInfo['product_list'][$optm]['productinfo']['picture'] = $orderInfo['product_list'][$optm]['productinfo']['thumb'];
                        $orderInfo['product_list'][$optm]['productinfo']['stock'] = $orderInfo['product_list'][$optm]['productinfo']['curriculum_num'];
                    }
                    break;
                case 2:
                    foreach($orderInfo['product_list'] as $optm=>$opst){
                        $orderInfo['product_list'][$optm]['productinfo'] = TeachingAidModel::where('id',$opst['product_id'])->first()->toArray();
                    }
                    break;
                case 3:
                    foreach($orderInfo['product_list'] as $optm=>$opst){
                        $orderInfo['product_list'][$optm]['productinfo'] = TeachingAidsModel::where('id',$opst['product_id'])->first()->toArray();
                    }
                case 4:
                    foreach($orderInfo['product_list'] as $optm=>$opst){
                        $orderInfo['product_list'][$optm]['productinfo'] = ActivityModel::where('id',$opst['product_id'])->first()->toArray();
                        $orderInfo['product_list'][$optm]['productinfo']['picture'] =
                            $orderInfo['product_list'][$optm]['productinfo']['thumb'];
                    }
            }

            unset($memberInfo);
            //订单状态 0 已取消 10 未付款 20 已付款 40 已发货 50 交易成功 60 交易失败

            foreach($orderInfo['product_list'] as $ptm=>$pst){
                $orderInfo['product_list'][$ptm]['amount'] = intval($pst['num'])*$pst['productinfo']['price'];
                $orderInfo['amount'][] = intval($pst['num'])*$pst['productinfo']['price'];
            }

            switch($orderInfo['pay_status']){
                case 10:
                    $orderInfo['status_name'] = '未付款';
                    break;
                case 20:
                    $orderInfo['status_name'] = '支付中';
                    break;
                case 40:
                    $orderInfo['status_name'] = '已付款';
                    break;
            }

            return $orderInfo;
        }
    }

    /**
     * 获取订单列表
     * @param int $pagesize
     * @return object $orderlist
     */
    public function getOrderList($pagesize,$member_id=0){
        $orderlist = OrderModel::orderBy('id','desc')
            ->where(function($query) use ($member_id){
                if($member_id > 0){
                    $query->where('member_id',$member_id);
                }
            })
            ->paginate($pagesize);

        foreach($orderlist as $otm=>$ost){
            $orderlist[$otm]->product_list = ProductOrderModel::where('order_id',$ost->id)->get();
            $memberInfo = MemberModel::where('id',$ost->member_id)->select('nick','telephone')->first();

            if(!empty($memberInfo)){
                if($ost->member_id > 116 && $memberInfo->nick == base64_encode(base64_decode($memberInfo->nick))){
                    $memberInfo->nick = base64_decode($memberInfo->nick);
                }
                $orderlist[$otm]->member_nick = $memberInfo->nick;
                $orderlist[$otm]->telephone = $memberInfo->telephone;
            }else{
                $orderlist[$otm]->member_nick = '';
                $orderlist[$otm]->telephone = '';
            }

            if($ost->t_mid > 0){
                $tMember = MemberModel::where('id',$ost->t_mid)->select('nick')->first();
                if(!empty($tMember)){
                    if($ost->t_mid > 116 && $tMember->nick == base64_encode(base64_decode($tMember->nick))){
                        $tMember->nick = base64_decode($tMember->nick);
                    }
                    $orderlist[$otm]->tmember_nick = $tMember->nick;
                }else{
                    $orderlist[$otm]->tmember_nick = '-';
                }
            }else{
                $orderlist[$otm]->tmember_nick = '-';
            }

            unset($memberInfo);
        }

        foreach($orderlist as $itm=>$lst){
            foreach($lst->product_list as $ptm=>$pst){
                if($lst->product_type == 2){
                    $info = TeachingAidModel::where('id',$pst->product_id)->select('name','desc','price')->first();
                }else if($lst->product_type == 4){
                    $info = ActivityModel::where('id',$pst->product_id)->select('name','desc','price')->first();
                }else{
                    $info = CourseModel::where('id',$pst->product_id)->select('name','desc','price')->first();
                }
                if(!empty($info)){
                    $orderlist[$itm]->product_list[$ptm]->product_name = $info->name;
                    $orderlist[$itm]->product_list[$ptm]->price = $info->price;
                    $orderlist[$itm]->product_list[$ptm]->amount = intval($pst->num)*$info->price;
                    $orderlist[$itm]->product_list[$ptm]->desc = $info->desc;
                }
            }
        }

        foreach($orderlist as $olm=>$olt){
            foreach($olt->product_list as $opm=>$opt){
                $orderlist[$olm]->order_amount += $opt->amount;
            }
        }
        return $orderlist;
    }


    /**
     * 获取销售总量
     * @return int $saleCount
     */
    public function getSaleCount($start_date='',$end_date=''){
        $orderlist = OrderModel::where('pay_status',40)
            ->where('composition_status', '>=', 30)
            ->where('composition_status', '<', 60)
            ->where(function($query) use ($start_date){
                if($start_date != ''){
                    $query->where('payment_time', '>=', $start_date);
                }
            })
            ->where(function($query) use ($end_date){
                if($end_date != ''){
                    $query->where('payment_time', '<=', $end_date);
                }
            })
            ->select('payment')
            ->get();

        if(!empty($orderlist)){
            $salelist = array();
            foreach($orderlist as $otm=>$ost){
                $salelist[] = $ost->payment;
            }

            $saleCount = array_sum($salelist);
        }else{
            $saleCount = 0;
        }

        return $saleCount;
    }

    /**
     * 修改订单状态
     * @param array $data
     * @return $res
     */
    public function updateOrder($id,$data){
        $res = OrderModel::where('id',$id)->update($data);
        return $res;
    }

}